package admin

import (
	"fmt"
	"gin-demo01/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"strconv"
)

type AdminController struct {
}

func (a AdminController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/userAdd.html", gin.H{})
}

func (a AdminController) Upload(c *gin.Context) {
	username := c.PostForm("username")
	file, err := c.FormFile("face")
	dst := path.Join("./static/upload", file.Filename)
	if err == nil {
		c.SaveUploadedFile(file, dst)
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "username": username, "dst": dst})
}

func (a AdminController) Edit(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/userEdit.html", gin.H{})
}

func (a AdminController) DoEdit(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("DoEdit 出错")
			c.String(http.StatusBadRequest, "DoEdit 出错")
		}
	}()
	username := c.PostForm("username")
	file, err := c.FormFile("face1")
	dst1 := path.Join("./static/upload", file.Filename)
	if err == nil {
		c.SaveUploadedFile(file, dst1)
	}
	file2, err2 := c.FormFile("face2")
	dst2 := path.Join("./static/upload", file2.Filename)
	if err2 == nil {
		c.SaveUploadedFile(file2, dst2)
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "username": username, "dst1": dst1, "dst2": dst2})
}

func (a AdminController) AddAll(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/userAddAll.html", gin.H{})
}

func (a AdminController) DoUploadAll(c *gin.Context) {
	username := c.PostForm("username")
	form, _ := c.MultipartForm()
	files := form.File["face[]"]

	for _, file := range files {
		extName := path.Ext(file.Filename)
		allowExtMap := map[string]bool{
			".jpg":  true,
			".jpeg": true,
			".png":  true,
			".gif":  true,
		}

		if _, ok := allowExtMap[extName]; !ok {
			c.String(http.StatusBadRequest, "请上传正确格式的图片")
		}

		day := models.GetDay()
		dir := "./static/upload/" + day
		err := os.MkdirAll(dir, 0666)
		if err != nil {
			fmt.Println(err)
			c.String(http.StatusBadRequest, "创建文件夹失败")
		}

		filename := strconv.FormatInt(models.GetUnix(), 10) + extName

		// 上传文件至指定目录
		dst := path.Join(dir, filename)
		c.SaveUploadedFile(file, dst)
	}
	c.String(http.StatusOK, fmt.Sprintf("%v %d files uploaded!", username, len(files)))
}
